package com.htandroid.htandroid.aty;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.ab.soap.AbSoapListener;
import com.ab.soap.AbSoapParams;
import com.ab.soap.AbSoapUtil;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.ioc.AbIocView;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.entity.MrqgdDjList;
import com.htandroid.htandroid.excel.ExcelPurchase_cfqgqd;
import com.htandroid.htandroid.sys.Basenvo;
import com.htandroid.htandroid.sys.InstorageURL;
import com.htandroid.htandroid.sys.User;
import com.htandroid.htandroid.sys.base_index;
import com.htandroid.htandroid.tools.ToolLog;
import com.htandroid.htandroid.webservice.BuildMrqgdXMLService;
import com.htandroid.htandroid.webservice.XMLMrqgdlist;
import com.htandroid.htandroid.webservice.abXMLMrqgdlist;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;

import static com.htandroid.htandroid.constance.ConstanceServer.BaseUrl_New;
import static com.htandroid.htandroid.excel.ExcelGetDir.getExcelDir;

/**
 * Created by lkp on 2015/11/29.
 */
public class mrqgd_index extends base_index {
    private ArrayList<MrqgdDjList> mrqgdlist;
    Integer listserial;
    private ArrayAdapter<String> adapter_ddate;//日期下拉列表
    ArrayList<String> list_ddate = new ArrayList<String>();
    LinearLayout foot_ly;

    @AbIocView(id = R.id.spinner_ddate)
    Spinner spinner_ddate;
    @AbIocView(id = R.id.btn1_tv, click = "btnClick")
    TextView btn1_tv;
    @AbIocView(id = R.id.btn2_tv, click = "btnClick")
    TextView btn2_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.layout_mrqgd_index);
        initview("厨房请购清单");
        initview2();
        getdata(0);
    }

    public void btnClick(View v) {
        switch (v.getId()) {
            case R.id.btn1_tv:
                mrqgd_his(v);
                break;
            case R.id.btn2_tv:
                mrqgd_save(v);
                break;
        }
    }

    //初始化2
    @Override
    public void initview2() {
        btn_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String excelName = "0".equals(listtype) ? "待叫货" : "未定价";
                excelPath = getExcelDir() + File.separator + "厨房请购清单" + excelName + ".xls";
                ExcelPurchase_cfqgqd cfqgqd = new ExcelPurchase_cfqgqd(mrqgd_index.this, excelPath, mrqgdlist, listtype);
                if (mrqgdlist == null) {
                    AbToastUtil.showToast(getApplicationContext(), "列表中没有数据，不能分享");
                } else {
                    OnekeyShare oks = new OnekeyShare();
                    oks.setTitle("厨房请购清单" + excelName + ".xls");
                    oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
                        @Override
                        public void onShare(Platform platform,
                                            cn.sharesdk.framework.Platform.ShareParams paramsToShare) {
                            // TODO Auto-generated method stub
                            if (platform.getName().equals("Wechat")) {
                                paramsToShare.setShareType(Platform.SHARE_FILE);
                            }
                        }
                    });
                    imgPath = getExcelDir() + File.separator + "excel.png";
                    writeImg(imgPath);
                    oks.setImagePath(imgPath);
                    oks.setFilePath(excelPath);
                    oks.show(getApplicationContext());
                }
            }
        });

        foot_ly = (LinearLayout) findViewById(R.id.foot_ly);
        foot_ly.setVisibility(View.GONE);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //处理选状态
                linechoose("r", Integer.valueOf("" + id));
                //获取list中的position号
                listserial = (int) id;
                //获取对象
                if (listtype.equals("0")) {
                    Intent intent = new Intent(getApplicationContext(), mrqgd_orderdetail.class);// 创建Intent对象
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("mrqgds", mrqgdlist.get(listserial));
                    intent.putExtras(bundle);
                    intent.putExtra("icurrentrow", listserial);//传递类型,下一界面便于控制
                    startActivityForResult(intent, R.layout.layout_mrqgd_orderdetail / 200000);// 执行Intent操作
                } else {
                    Intent intent = new Intent(getApplicationContext(), mrqgd_djdetail.class);// 创建Intent对象
                    //传递参数
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("mrqgdlist", mrqgdlist);
                    intent.putExtras(bundle);
                    intent.putExtra("icurrentrow", listserial);//传递类型,下一界面便于控制
                    startActivityForResult(intent, R.layout.layout_mrqgd_djdetail / 100000);
                }
            }
        });

        //到货日期下拉
        //spinner_ddate = (Spinner) findViewById(R.id.spinner_ddate);
        adapter_ddate = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list_ddate);
        adapter_ddate.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_ddate.setAdapter(adapter_ddate);
        //设置日期切换监听
        spinner_ddate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                getdata(0);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //到货日期初始化
        getdhdate();
    }

    //填充到货日期
    private void getdhdate() {
//        TreeMap<String, String> properties = new TreeMap<String, String>();
//        //参数
//        //String[] parms = {"usercode","cacc_id","iyear","ddate"};
//        properties.put("arg0", User.uid);
//        properties.put("arg1", myApplication.getGs_ztid());
//        properties.put("arg2", myApplication.getGs_year());
//        properties.put("arg3", myApplication.getGs_sj());
//        ToolSOAP.callService("mrqgd_ddhdatelist", properties, new ToolSOAP.WebServiceCallBack() {
//            @Override
//            public void onSucced(SoapObject result) {
//                list_ddate.clear();
//                if (result != null) {
//                    for (int i = 0; i < result.getPropertyCount(); i++) {
//                        SoapObject item = (SoapObject) result.getProperty(i);
//                        for (int j = 0; j < item.getPropertyCount(); j++) {
//                            list_ddate.add(item.getPropertyAsString(j));
//                        }
//                    }
//                } else {
//                    AbToastUtil.showToast(getApplicationContext(), R.string.sqlerrormsg);
//                }
//                //使用这个函数直接根据返回结果刷新列表
//                adapter_ddate.notifyDataSetChanged();
//                //loadingDialog.loadingfinish();
//            }
//
//            @Override
//            public void onFailure(String result) {
//                //loadingDialog.loadingfinish();
//                AbToastUtil.showToast(getApplicationContext(), R.string.sqlerrormsg);
//            }
//        });

        String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;//旧版webservice地址
        AbSoapParams params = new AbSoapParams();
        params.put("arg0", User.uid);
        params.put("arg1", myApplication.getGs_ztid());
        params.put("arg2", myApplication.getGs_year());
        params.put("arg3", myApplication.getGs_sj());
        mAbSoapUtil.call(urlString, InstorageURL.NAME_SPACE, "mrqgd_ddhdatelist", params, new AbSoapListener() {
            //获取数据成功会调用这里
            @Override
            public void onSuccess(int statusCode, String content) {
                list_ddate.clear();
                if (content != null) {
                    if (content.contains("anyType{}")) {
                        list_ddate.add("");
                    } else {
                        String str = content.split("anyType")[1].split("=")[1].split(";")[0];
                        list_ddate.add(str);
                    }
                } else {
                    AbToastUtil.showToast(getApplicationContext(), R.string.sqlerrormsg);
                }
                adapter_ddate.notifyDataSetChanged();
                //AbDialogUtil.removeDialog(mrqgd_index.this);
            }

            // 失败，调用
            @Override
            public void onFailure(int statusCode, String content,
                                  Throwable error) {
                AbToastUtil.showToast(mrqgd_index.this, R.string.sqlerrormsg);
            }

            // 开始执行前
            @Override
            public void onStart() {
                //显示进度框
                //AbDialogUtil.showProgressDialog(mrqgd_index.this, 0, "正在加载...");
            }

            // 完成后调用，失败，成功
            @Override
            public void onFinish() {
                //移除进度框
                //AbDialogUtil.removeDialog(mrqgd_index.this);
            }
        });
    }

    //获取数据
    @Override
    public void getdata(int page) {
        if (spinner_ddate.getItemAtPosition(spinner_ddate.getSelectedItemPosition()) == null) {
            return;
        }
        final String ddhdate = spinner_ddate.getItemAtPosition(spinner_ddate.getSelectedItemPosition()).toString();
        //根据状态隐藏按钮
        if (listtype.equals("0")) {
            foot_ly.setVisibility(View.GONE);
        } else {
            foot_ly.setVisibility(View.VISIBLE);
        }
        String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;//旧版webservice地址
        AbSoapParams params = new AbSoapParams();
        params.put("arg0", User.uid);
        params.put("arg1", myApplication.getGs_ztid());
        params.put("arg2", myApplication.getGs_year());
        params.put("arg3", myApplication.getGs_sj());
        params.put("arg4", ddhdate);
        params.put("arg5", listtype);
        adatperDataList.clear();
        mAbSoapUtil.call(urlString, InstorageURL.NAME_SPACE, "mrqgd_list", params, new AbSoapListener() {
            //获取数据成功会调用这里
            @Override
            public void onSuccess(int statusCode, String content) {
                ToolLog.log("+++++++++++++++++++++++++++++++++++:" + content);
                adatperDataList.clear();
                if (content != null) {
                    mrqgdlist = abXMLMrqgdlist.paraseCommentInfors(content);
                    insert_data();
                } else {
                    AbToastUtil.showToast(getApplicationContext(), R.string.sqlerrormsg);
                }
                AbDialogUtil.removeDialog(mrqgd_index.this);
            }

            // 失败，调用
            @Override
            public void onFailure(int statusCode, String content,
                                  Throwable error) {
                AbToastUtil.showToast(mrqgd_index.this, R.string.sqlerrormsg);
            }

            // 开始执行前
            @Override
            public void onStart() {
                //显示进度框
                AbDialogUtil.showProgressDialog(mrqgd_index.this, 0, "正在加载...");
            }

            // 完成后调用，失败，成功
            @Override
            public void onFinish() {
                //移除进度框
                AbDialogUtil.removeDialog(mrqgd_index.this);
            }
        });
    }

    //接收返回数据(叫货和定价返回)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case R.layout.layout_mrqgd_djdetail / 100000:
                if (data != null) {
                    //刷新list
                    Bundle bundle = data.getExtras();
                    MrqgdDjList mrqgds1 = new MrqgdDjList();
                    if (bundle != null) {
                        mrqgds1 = (MrqgdDjList) bundle.getSerializable("mrqgds");
                    }
                    //更新实例变量中的记录
                    MrqgdDjList mrqgds = (MrqgdDjList) mrqgdlist.get(listserial);
                    //设置值相等
                    mrqgdlist.get(listserial).setobject(mrqgds1);
                    //mrqgds.equal(mrqgds1);
                    mrqgds1 = mrqgdlist.get(listserial);
                    //刷新当前格内数据
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("index", (listserial + 1));
                    map.put("cvouchid", "存货：" + mrqgds1.getcInvname());
                    map.put("cdept", "规格：" + mrqgds1.getcInvstd());
                    map.put("cnocheckreason", "计量单位：" + Basenvo.space_add(mrqgds1.getcInvm_unit(), 8, 0) + "备注：" + mrqgds1.getCmemo());
                    map.put("ddate", "数量：" + Basenvo.space_add(Basenvo.customFormat("#####0.00##", mrqgds1.getiQuantity()), 12, 0) + "单价：" + Basenvo.space_add(Basenvo.customFormat("#####0.00##", mrqgds1.getIprice()), 12, 1));
                    //更多数据
                    map.put("data5", "金额：" + Basenvo.customFormat("#####0.00##", mrqgds1.getIamount()));
                    map.put("data6", "请购部门：" + mrqgds1.getCdepname());
                    map.put("data7", "存货分类：" + mrqgds1.getcInvcName());
                    map.put("data8", "供应商：" + mrqgds1.getCvenname());
                    //ArrayList<Map<String, Object>> dataListForInit = new ArrayList<Map<String, Object>>();
                    //adatperDataList.set(listserial,map);
                    toolDataProvider.setDataByIndex(listserial, map);
                    loadList();
                    //mHandler.sendEmptyMessage(LIST_GET_FIRST_PAGE);
                    //swipeRefreshLayout.setRefreshing(false);
                }
                break;
            case R.layout.layout_mrqgd_orderdetail / 200000:
                //全叫货完成,或者全删除后的刷新
                getdata(0);
                break;
            case R.layout.basenvo_nofunc / 300000:
                //处理选状态
                linechoose("r", data.getExtras().getInt("currentrow"));
                break;
            default:
                //其它窗口的回传数据
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //保存定价信息
    public void mrqgd_save(View v) {
        Boolean isdj = false;
        //先判断是否所有存货都未定价
        for (int i = 0; i < mrqgdlist.size(); i++) {
            MrqgdDjList mrqgd = (MrqgdDjList) mrqgdlist.get(i);
            String cvencode = mrqgd.getCvencode();
            if (cvencode != null && !cvencode.equals("")) {
                isdj = true;
                break;
            }
        }
        //查看是否存在定价记录.若全未定价也允许保存则后续将提示保存失败
        if (!isdj) {
            AbToastUtil.showToast(getApplicationContext(), "未进行存货定价!");
            return;
        }
        //参数
        String urlString = "http://" + InstorageURL.SERVERURL
                + BaseUrl_New;
        String ddhdate = spinner_ddate.getItemAtPosition(spinner_ddate.getSelectedItemPosition()).toString();
        String[] parms = {"user", "cacc_id", "iyear", "ddate", "ddate_dh"};
        String[] vals = {User.nickName, myApplication.getGs_ztid(), myApplication.getGs_year(), myApplication.getGs_sj(), ddhdate};
        //生成xml
        BuildMrqgdXMLService service = new BuildMrqgdXMLService();
        String xmlstring = service.buildXML("mrqgd_dj_ok", InstorageURL.NAME_SPACE, parms, vals, "in" + parms.length, mrqgdlist);
        mAbSoapUtil.xmlCall(urlString, InstorageURL.NAME_SPACE, "mrqgd_dj_ok", xmlstring, new AbSoapUtil.WebServiceCallBack() {
            @Override
            public void onSucced(String result) {
                adatperDataList.clear();
                if (result != null) {
                    //解析xml文件,返回列表
                    ArrayList<MrqgdDjList> mrqgdlisttemp = XMLMrqgdlist.paraseCommentInfors(result);
                    //对比list是否发生变化
                    Boolean issame = true;
                    //对象列表内容长度如果一样则还需要比较详细内容
                    if (mrqgdlisttemp.size() == mrqgdlist.size()) {
                        for (int i = 0; i < mrqgdlist.size(); i++) {
                            MrqgdDjList mrqgdtemp = mrqgdlisttemp.get(i);
                            MrqgdDjList mrqgd = mrqgdlisttemp.get(i);
                            if (!mrqgd.equals(mrqgdtemp)) {
                                issame = false;
                                break;
                            }
                        }
                    } else {
                        issame = false;
                    }
                    if (issame) {
                        AbToastUtil.showToast(getApplicationContext(), "定价数据保存失败!");
                        return;
                    } else {
                        //准备重新创建列表
                        mrqgdlist = mrqgdlisttemp;
                    }
                    insert_data();
                } else {
                    AbToastUtil.showToast(getApplicationContext(), "定价数据保存失败!数据库错误!");
                }
            }

            @Override
            public void onFailure(String result) {
                AbToastUtil.showToast(getApplicationContext(), "定价数据保存失败!数据库错误!");
            }
        });
    }

    //厨房请购历史定价
    public void mrqgd_his(View v) {
        //判断有没有历史定价的权限
        if (!myApplication.authfind("QG02010303")) {
            AbToastUtil.showToast(getApplicationContext(), "您没有历史定价权限!");
            return;
        }
        //刷新列表
        String urlString = "http://" + InstorageURL.SERVERURL
                + BaseUrl_New;
        String[] parms = {"user", "cacc_id", "iyear"};
        String[] vals = {User.nickName, myApplication.getGs_ztid(), myApplication.getGs_year()};
        //生成xml
        BuildMrqgdXMLService service = new BuildMrqgdXMLService();
        String xmlstring = service.buildXML("mrqgd_dj_his", InstorageURL.NAME_SPACE, parms, vals, "in" + parms.length, mrqgdlist);
        mAbSoapUtil.xmlCall(urlString, InstorageURL.NAME_SPACE, "mrqgd_dj_his", xmlstring, new AbSoapUtil.WebServiceCallBack() {
            @Override
            public void onSucced(String result) {
                adatperDataList.clear();
                if (result != null) {
                    //解析xml文件,返回列表
                    mrqgdlist = XMLMrqgdlist.paraseCommentInfors(result);
                    insert_data();
                } else {
                    AbToastUtil.showToast(getApplicationContext(), R.string.sqlerrormsg);
                }
            }

            @Override
            public void onFailure(String result) {
                AbToastUtil.showToast(getApplicationContext(), R.string.sqlerrormsg);
                //ToolLog.log("err：" + result);
            }
        });
    }

    public void insert_data() {
        ArrayList<Map<String, Object>> dataListForInit = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < mrqgdlist.size(); i++) {
            //增加一个行选择状态初始化
            sa.getIsSelected().put(i, false);
            MrqgdDjList mrqgd = new MrqgdDjList();
            mrqgd = mrqgdlist.get(i);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("index", (i + 1));
            //定价和叫货的显示格式不一样
            if (listtype.equals("0")) {
                map.put("cvouchid", "名称：" + mrqgd.getCvenname());
                map.put("cdept", "简称：");
                map.put("cnocheckreason", "联系电话：" + mrqgd.getCventel());
                map.put("ddate", "Emali：" + mrqgd.getCvenemail());
                map.put("more", "0");
            } else {
                map.put("cvouchid", "存货：" + mrqgd.getcInvname());
                map.put("cdept", "规格：" + mrqgd.getcInvstd());
                map.put("cnocheckreason", "计量单位：" + Basenvo.space_add(mrqgd.getcInvm_unit(), 8, 0) + "备注：" + mrqgd.getCmemo());
                map.put("ddate", "数量：" + Basenvo.space_add(Basenvo.customFormat("#####0.00##", mrqgd.getiQuantity()), 12, 0) + "单价：" + Basenvo.space_add(Basenvo.customFormat("#####0.00##", mrqgd.getIprice()), 12, 1));
                //更多数据
                map.put("data5", "金额：" + Basenvo.customFormat("#####0.00##", mrqgd.getIamount()));
                map.put("data6", "请购部门：" + mrqgd.getCdepname());
                map.put("data7", "存货分类：" + mrqgd.getcInvcName());
                map.put("data8", "供应商：" + mrqgd.getCvenname());
            }
            dataListForInit.add(map);
        }
        toolDataProvider.initData(dataListForInit);
        loadList();
        //mHandler.sendEmptyMessage(LIST_GET_FIRST_PAGE); //加载完毕发送指令显示第一页
        //swipeRefreshLayout.setRefreshing(false);
    }
}
